package com.yuexun.dhdoctor.module.commun.ui;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.view.View;
import android.widget.Button;
import android.widget.GridView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.yuexun.dhdoctor.R;
import com.yuexun.dhdoctor.base.AppContext;
import com.yuexun.dhdoctor.base.BaseKJActivity;
import com.yuexun.dhdoctor.baselistener.OnDataBackListener;
import com.yuexun.dhdoctor.config.AppConfig;
import com.yuexun.dhdoctor.module.Contract.adapter.CreateGroupAdapter;
import com.yuexun.dhdoctor.module.Contract.bean.DepartOrPeopleData;
import com.yuexun.dhdoctor.module.Contract.bean.People;
import com.yuexun.dhdoctor.module.Contract.ui.Act_Hospital_Select;
import com.yuexun.dhdoctor.module.commun.ui.fragment.Frag_Choice_Department;
import com.yuexun.dhdoctor.module.commun.ui.fragment.Frag_Choice_Group;
import com.yuexun.dhdoctor.module.commun.ui.fragment.Frag_Choice_people;
import com.yuexun.dhdoctor.widget.ToastDialog;

import org.kymjs.kjframe.utils.PreferenceHelper;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;


/**
 * Created by Administrator on 2017/3/27 0027.
 */

public class Act_Choice_Member extends BaseKJActivity implements OnDataBackListener {

    @Bind(R.id.groupTitle)
    Button groupTitle;
    @Bind(R.id.depTitle)
    Button depTitle;
    @Bind(R.id.contactTitle)
    Button contactTitle;
    @Bind(R.id.grid)
    GridView grid;
    @Bind(R.id.addmember_sure_btn)
    TextView addmemberSureBtn;
    @Bind(R.id.title_tv)
    TextView titleTv;
    @Bind(R.id.txt_hospitalName)
    TextView hospitalNameTxt;
    @Bind(R.id.select_hospital)
    TextView select_hospital;

    String title;
    String type;
    //0：不能选择  1：能选择自己
    private int isSelectMe;
    int from;//0多选 1单选
    public ArrayList<People> usersBeans_origin = new ArrayList<>();

    int newView = 1;
    Frag_Choice_Department departmentActivity;
    Frag_Choice_Group groupActivity;
    Frag_Choice_people peopleActivity;
    CreateGroupAdapter adapter;

    String hospitalName;
    public static int hospitalId;
    MyBroadcastReceiver mBroadcastReceiver;

    public class MyBroadcastReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            hospitalName = intent.getExtras().getString("hospitalName");
            hospitalId = intent.getExtras().getInt("hospitalId");
            hospitalNameTxt.setText(hospitalName);
            if (hospitalId == PreferenceHelper.readInt(aty, AppConfig.USER_INFO, AppConfig.HOSPITALID)) {
                Drawable drawable = getResources().getDrawable(R.drawable.icon_this_court);
                /// 这一步必须要做,否则不会显示.
                drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
                select_hospital.setCompoundDrawables(drawable, null, null, null);
                hospitalNameTxt.setVisibility(View.GONE);
            } else {
                Drawable drawable = getResources().getDrawable(R.drawable.icon_other_court);
                /// 这一步必须要做,否则不会显示.
                drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
                select_hospital.setCompoundDrawables(drawable, null, null, null);
                hospitalNameTxt.setVisibility(View.VISIBLE);
            }

            if (newView == 1) {
                peopleActivity.setHospitalId(hospitalId);
            } else if (newView == 2) {
                departmentActivity.setHospitalId(hospitalId);
            }
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        mBroadcastReceiver = new MyBroadcastReceiver();
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction("com.MyBroadcastReceiver");
        registerReceiver(mBroadcastReceiver, intentFilter);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        unregisterReceiver(mBroadcastReceiver);
    }

    @Override
    public void setRootView() {
        super.setRootView();
        setContentView(R.layout.act_choice_member);
        ButterKnife.bind(this);
    }

    @Override
    public void initData() {
        usersBeans_origin = (ArrayList<People>) getIntent().getExtras().getSerializable("persons");
        title = getIntent().getExtras().getString("title");
        type = getIntent().getExtras().getString("type");
        isSelectMe = getIntent().getExtras().getInt("isSelectMe", 0);

        hospitalName = PreferenceHelper.readString(aty, AppConfig.USER_INFO, AppConfig.HOSPITALNAME);
        hospitalId = PreferenceHelper.readInt(aty, AppConfig.USER_INFO, AppConfig.HOSPITALID);

        if (type.equals("多选")) {
            from = 0;
        } else {
            from = 1;
        }
        if (title.isEmpty()) {
            select_hospital.setVisibility(View.VISIBLE);
        } else {
            select_hospital.setVisibility(View.GONE);
        }

        titleTv.setText(title);

        departmentActivity = new Frag_Choice_Department();
        groupActivity = new Frag_Choice_Group();
        peopleActivity = new Frag_Choice_people();
        groupActivity.setUsersBeans_origin(usersBeans_origin, this, from, isSelectMe);
        peopleActivity.setUsersBeans_origin(usersBeans_origin, this, from, isSelectMe);
        departmentActivity.setUsersBeans_origin(usersBeans_origin, this, from, isSelectMe);
        groupTitle.setSelected(true);

        newView = 1;
        changeFragment(R.id.group_content, peopleActivity);
        setGridView();
    }

    @Override
    public void showData(Bundle bundle) {
        if (bundle != null) {
            usersBeans_origin = (ArrayList<People>) bundle.getSerializable("usersBeans");
            setGridView();
        }
    }

    @OnClick({R.id.back, R.id.groupTitle, R.id.depTitle, R.id.contactTitle,
            R.id.addmember_sure_btn, R.id.select_hospital})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.back:
                finish();
                break;
            case R.id.groupTitle:
                newView = 1;
                changeFragment(R.id.group_content, peopleActivity);
                groupTitle.setSelected(true);
                depTitle.setSelected(false);
                contactTitle.setSelected(false);
                break;
            case R.id.depTitle:
                newView = 2;
                changeFragment(R.id.group_content, departmentActivity);
                groupTitle.setSelected(false);
                depTitle.setSelected(true);
                contactTitle.setSelected(false);
                break;
            case R.id.contactTitle:
                newView = 3;
                changeFragment(R.id.group_content, groupActivity);
                groupTitle.setSelected(false);
                depTitle.setSelected(false);
                contactTitle.setSelected(true);
                break;
            case R.id.addmember_sure_btn:
                if (usersBeans_origin.size() == 0) {
                    Toast.makeText(this, "请选择接收对象", Toast.LENGTH_SHORT).show();
                } else {
                    if (from == 1 && usersBeans_origin.size() > 1) {
                        Toast.makeText(this, "只能选择一个", Toast.LENGTH_SHORT).show();
                        break;
                    }

                    if (isSelectMe == 0) {
                        if (!PreferenceHelper.readString(AppContext.getInstance(), AppConfig.USER_INFO, AppConfig.JOB_ID)
                                .equals(usersBeans_origin.get(0).getJobNum())) {
                            Bundle bundle = new Bundle();
                            Intent intent = new Intent();
                            bundle.putSerializable("persons", usersBeans_origin);
                            intent.putExtras(bundle);
                            setResult(10000, intent);
                            finish();
                        } else {
                            new ToastDialog(aty, "不能选择自己为接收对象!").show();
                        }
                    } else {
                        Bundle bundle = new Bundle();
                        Intent intent = new Intent();
                        bundle.putSerializable("persons", usersBeans_origin);
                        intent.putExtras(bundle);
                        setResult(10000, intent);
                        finish();
                    }
                }
                break;
            case R.id.select_hospital:
                Bundle bundle = new Bundle();
                Intent intent = new Intent(aty, Act_Hospital_Select.class);
                bundle.putString("newHospital", hospitalName);
                bundle.putInt("newHospitalId", hospitalId);
                bundle.putInt("strHospitalId", 1);
                intent.putExtras(bundle);
                startActivity(intent);
                break;
        }
    }

    private void setGridView() {
        int size = usersBeans_origin.size();

        if (size == 0) {
            addmemberSureBtn.setClickable(false);
            addmemberSureBtn.setBackgroundResource(R.color.line);
            addmemberSureBtn.setText("确认");
        } else {
            addmemberSureBtn.setClickable(true);
            addmemberSureBtn.setBackgroundResource(R.color.app_theme_color);
            addmemberSureBtn.setText("确认(" + size + "人)");
        }


        int length = 80;

        DisplayMetrics dm = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(dm);
        float density = dm.density;
        int gridviewWidth = (int) (size * (length + 4) * density);
        int itemWidth = (int) (length * density);

        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
                gridviewWidth, LinearLayout.LayoutParams.FILL_PARENT);
        grid.setLayoutParams(params); // 重点
        grid.setColumnWidth(itemWidth); // 重点
        grid.setHorizontalSpacing(5); // 间距
        grid.setStretchMode(GridView.NO_STRETCH);
        grid.setNumColumns(size); // 重点

        List<DepartOrPeopleData> datas = new ArrayList<>();
        for (People people : usersBeans_origin) {
            DepartOrPeopleData data = new DepartOrPeopleData();
            data.setDataId(people.getUserId() + "");
            data.setDataName(people.getUserName());
            datas.add(data);
        }

        adapter = new CreateGroupAdapter(grid, datas, R.layout.item_send_addmember);
        grid.setAdapter(adapter);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (resultCode) {
            case 10000:
                usersBeans_origin = (ArrayList<People>) data.getExtras().getSerializable("persons");
                finishView(usersBeans_origin);
                break;
            case 10001:
                usersBeans_origin = (ArrayList<People>) data.getExtras().getSerializable("persons");
                finishView(usersBeans_origin);
                break;
            case 0x001:
                usersBeans_origin = ((ArrayList<People>) data.getExtras().getSerializable("persons"));
                setGridView();
                break;
        }
    }

    private void finishView(ArrayList<People> usersBeans_origin) {
        setGridView();
        if (usersBeans_origin.size() == 0) {
            Toast.makeText(this, "请选择接收对象", Toast.LENGTH_SHORT).show();
        } else if (from == 1 && usersBeans_origin.size() > 1) {
            Toast.makeText(this, "只能选择一个", Toast.LENGTH_SHORT).show();
        } else {
            Bundle bundle = new Bundle();
            Intent intent = new Intent();
            bundle.putSerializable("persons", usersBeans_origin);
            intent.putExtras(bundle);
            setResult(10000, intent);
            finish();
        }
    }

}
